<template>
  <div class="app-container">
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd(true,null)"
          v-hasPermi="['mall-manager:category:add']"
        >添加一级分类</el-button>
      </el-col>
    </el-row>
      <el-table
        v-loading="loading"
        :data="tableData"
        style="width: 100%;margin-bottom: 20px;"
        row-key="id"
        border
        :tree-props="{children: 'children', hasChildren: 'hasChildren'}">
        <el-table-column
          prop="name"
          label="分类名称"
          >
        </el-table-column>
        <el-table-column
          prop="name"
          label="分类图标"
        >
          <template slot-scope="scope">
            <el-image style="width: 60px" fit="contain" :src="scope.row.image"></el-image>
          </template>
        </el-table-column>
        <el-table-column
          prop="level"
          label="分类层级"
        >
        </el-table-column>
        <el-table-column
          prop="isEnable"
          label="是否启用"
          >
          <template slot-scope="scope">
            <dict-tag :options="dict.type.sys_is_enable" :value="scope.row.isEnable"/>
          </template>
        </el-table-column>
        <el-table-column
          prop="commissionRate"
          label="佣金">
          <template slot-scope="scope">
            {{scope.row.commissionRate}}%
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-dropdown trigger="click">
            <span class="el-dropdown-link">
              更多<i class="el-icon-arrow-down el-icon--right"></i>
            </span>
              <el-dropdown-menu slot="dropdown" >
                <el-dropdown-item v-hasPermi="['mall-manager:category:add']" v-if="scope.row.level < 3">
                  <el-button
                    size="mini"
                    type="text"
                    icon="el-icon-plus"
                    @click="handleAdd(false,scope.row)"
                  >新增下级
                  </el-button>
                </el-dropdown-item>
                <el-dropdown-item v-hasPermi="['mall-manager:category:chgEnable']" v-if="scope.row.isEnable == 1">
                  <el-button
                    size="mini"
                    type="text"
                    icon="el-icon-close"
                    @click="handleChgEnable(scope.row,0)"
                  >禁用
                  </el-button>
                </el-dropdown-item>
                <el-dropdown-item v-hasPermi="['mall-manager:category:chgEnable']" v-if="scope.row.isEnable == 0">
                  <el-button
                    size="mini"
                    type="text"
                    icon="el-icon-check"
                    @click="handleChgEnable(scope.row,1)"
                  >启用
                  </el-button>
                </el-dropdown-item>
                <el-dropdown-item  v-hasPermi="['mall-manager:category:edit']">
                  <el-button
                    size="mini"
                    type="text"
                    icon="el-icon-edit"
                    @click="handleUpdate(scope.row)"
                  >修改
                  </el-button>
                </el-dropdown-item>
                <el-dropdown-item v-hasPermi="['mall-manager:category:remove']">
                  <el-button
                    size="mini"
                    type="text"
                    icon="el-icon-delete"
                    @click="handleDelete(scope.row)"
                  >删除
                  </el-button>
                </el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
            <el-dropdown trigger="click" v-if="scope.row.level == 3" style="margin-left: 20px">
            <span class="el-dropdown-link">
              绑定<i class="el-icon-arrow-down el-icon--right"></i>
            </span>
              <el-dropdown-menu slot="dropdown" >
                <el-dropdown-item v-hasPermi="['mall-manager:category:bind-brand']">
                  <el-button
                    size="mini"
                    type="text"
                    @click="handBrandBind(scope.row)"
                  >绑定品牌
                  </el-button>
                </el-dropdown-item>
                <el-dropdown-item v-hasPermi="['mall-manager:category:bind-spec']" >
                  <el-button
                    size="mini"
                    type="text"
                    @click="handSpecBind(scope.row)"
                  >绑定规格
                  </el-button>
                </el-dropdown-item>
                <el-dropdown-item v-hasPermi="['mall-manager:category:bind-param']" >
                  <el-button
                    size="mini"
                    type="text"
                    @click="handleParameterBind(scope.row)"
                  >绑定参数
                  </el-button>
                </el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>

    <!--  维护分类  -->
    <el-dialog :title="title" :visible.sync="open" v-if="open" width="50%" @close="open = false" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="90px">
        <el-form-item label="上级分类" prop="parentId">
          {{parentTitle}}
        </el-form-item>
        <el-form-item label="分类名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入分类名称" />
        </el-form-item>
        <el-form-item label="分类图标" prop="image">
          <UploadPicInput :file-type="fileType" :value="form.image" :file-size="fileSize" @input="uploadSuccess"></UploadPicInput>
        </el-form-item>
        <el-form-item label="排序值" prop="sortOrder">
          <el-input type="number" v-model="form.sortOrder" placeholder="请输入排序值" />
        </el-form-item>
        <el-form-item label="佣金比例(%)" prop="commissionRate">
          <el-input type="number" placeholder="请输入佣金比例(%)" v-model="form.commissionRate">
            <template slot="append">%</template>
          </el-input>
        </el-form-item>
        <el-form-item label="是否启用" prop="isEnable">
          <el-select v-model="form.isEnable" placeholder="请选择是否启用" clearable size="small" >
            <el-option
              v-for="dict in dict.type.sys_is_enable"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="分类备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="open = false">取 消</el-button>
      </div>
    </el-dialog>
    <!--  品牌关联  -->
    <el-dialog title="品牌关联" :visible.sync="brandBindOpen" v-if="brandBindOpen" width="50%" @close="brandBindOpen = false" append-to-body>
      <el-form ref="brandForm" :model="brandForm" :rules="rules" label-width="90px">

        <el-form-item label="关联品牌" prop="isEnable">
          <el-select v-model="brandForm.categoryBrands" placeholder="请选择关联品牌"
                     multiple
                     filterable
                     clearable size="small"
          style="width: 100%">
            <el-option
              v-for="brand in brandOps"
              :key="brand.id"
              :label="brand.name"
              :value="brand.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitBrandForm">确 定</el-button>
        <el-button @click="brandBindOpen = false">取 消</el-button>
      </div>
    </el-dialog>

    <!--  规格关联  -->
    <el-dialog title="规格关联" :visible.sync="specBindOpen" v-if="specBindOpen" width="50%" @close="specBindOpen = false" append-to-body>
      <el-form ref="specForm" :model="specForm" :rules="rules" label-width="90px">

        <el-form-item label="关联规格" prop="isEnable">
          <el-select v-model="specForm.categorySpecs" placeholder="请选择关联规格"
                     multiple
                     filterable
                     clearable size="small"
                     style="width: 100%">
            <el-option
              v-for="spec in specOps"
              :key="spec.id"
              :label="spec.specName"
              :value="spec.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitSpecForm">确 定</el-button>
        <el-button @click="specBindOpen = false">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>
<script>
import {
  addCategory,
  editCategory,
  delCategory,
  listCategoryBrands,
  listCategorySpecs,
  saveCategoryBrand,
  chgCategoryEnable,
  bindCategorySpec,
  getCategoryAll
} from "@/api/mall/goods/category";
import {listBrandsAll} from "@/api/mall/goods/brand";
import {listSpecAll} from "@/api/mall/goods/spec";
import UploadPicInput from '@/components/UploadPicInput'
export default {
  name: "goods-category",
  components: {UploadPicInput},
  dicts: ['sys_is_enable'],
  data() {
    return {
      categoryList: [], // 分类列表
      loading: false, // 加载状态
      brands: [], //品牌集合
      categoryId: "", // 分类id
      categorySpecs: [], //已经选择的规格
      parentTitle: "", // 父级菜单名称
      brandForm: {
        categoryId : undefined,
        categoryBrands: [],
      },
      brandOps: [], //请求绑定品牌的信息
      specOps: [], //请求绑定规格的信息
      // 规格数据
      specForm: {
        categoryId : undefined,
        categorySpecs: [],
      },
      tableData: [], // 表格数据
      title: '',
      open: false,
      brandBindOpen: false,
      specBindOpen: false,
      form: {},
      rules: {
        name: [
          { required: true, message: "分类名称不能为空", trigger: "blur" },
          { min: 1, max: 20, message: '分类名称必须小于20个字符', trigger: 'blur' }
        ],
      },
      fileType: ['png', 'jpg', 'jpeg'],
      fileSize: 2,
    };
  },
  mounted() {
    this.getBrandList();
    this.getSpecList();
  },
  created() {
    this.getAllList(0);
  },
  methods: {
    //获取所有品牌
    getBrandList() {
      listBrandsAll().then((res) => {
        this.brandOps = res.data;
      });
    },
    //获取所有规格
    getSpecList() {
      listSpecAll().then((res) => {
        this.specOps = res.data;
      });
    },
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            editCategory(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getAllList();
            });
          } else {
            addCategory(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getAllList();
            });
          }
        }
      });
    },
    // 品牌关联按钮操作
    handBrandBind(row) {
      listCategoryBrands(row.id).then((res) => {
        this.brandForm.categoryId = row.id;
        this.brandForm.categoryBrands = res.data.map((item) => item.id);
        this.brandBindOpen = true;
      });
    },
    // 规格关联按钮操作
    handSpecBind(row) {
      listCategorySpecs(row.id).then((res) => {
        this.specForm.categoryId = row.id;
        this.specForm.categorySpecs = res.data.map((item) => item.id);
        this.specBindOpen = true;
      });
    },
    /** 启停按钮操作 */
    handleChgEnable(row,isEnable) {
      const id = row.id;
      let enableDesp = 1 == isEnable ? '启用' : '禁用'
      this.$modal.confirm('是否确认'+enableDesp+'编号为"' + id + '"的数据项？').then(function() {
        let param = {
          id: id,
          isEnable: isEnable
        }
        return chgCategoryEnable(param);
      }).then(() => {
        this.getAllList();
        this.$modal.msgSuccess(enableDesp + "操作成功");
      }).catch(() => {});
    },
    //保存分类品牌绑定
    submitBrandForm() {
      saveCategoryBrand(this.brandForm).then((res) => {
        this.$modal.msgSuccess( "操作成功");
        this.brandBindOpen = false;
      });
    },
    //保存分类规格绑定
    submitSpecForm() {
      bindCategorySpec(this.specForm).then((res) => {
        this.$modal.msgSuccess( "操作成功");
        this.specBindOpen = false;
      });
    },
    // 参数绑定按钮操作
    handleParameterBind(row) {
      this.$router.push({
        path: '/mall/goods/relate/parameter',
        query: {
          categoryId: row.id
        }
      })
    },
    // 编辑分类
    handleUpdate(row) {
      this.title = "修改分类";
      this.form = row;
      this.open = true;
    },
    // 添加分类
    handleAdd(addFirst,row) {
      this.reset();
      if (addFirst){
        this.title = "添加一级分类";
        this.parentTitle = "顶级分类";
      }else{
        this.title = "添加子分类";
        this.parentTitle = row.name;
        this.form.level = eval(row.level + "+1");
        this.form.commissionRate = row.commissionRate;
        this.form.parentId = row.id;
      }
      this.open = true;
    },
    reset(){
      this.form = {
        name: "",
        level: 1,
        parentId: 0,
        sortOrder: 0,
        commissionRate: 0,
        isEnable: 0,
        image: undefined,
        remark: '',
      };
      this.resetForm("form");
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除编号为"' + ids + '"的数据项？').then(function() {
        return delCategory(ids);
      }).then(() => {
        this.getAllList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },

    // 获取分类数据
    getAllList(parent_id) {
      this.loading = true;
      getCategoryAll(parent_id).then((res) => {
        this.tableData = this.handleTree(res.data, "id");
        this.loading = false;
      });
    },
    uploadSuccess(res){
      this.form.image = res;
    },
  },

};
</script>
<style lang="scss" scoped>
  ::v-deep .ivu-table-wrapper {
    overflow: auto;
  }
.table {
  min-height: 100vh;
  height: auto;
}
</style>
